#include"list.h"

struct List create(int isize){
	struct List list1;
	list1.pdatas = (DE*)malloc(isize*sizeof(DE));
	list1.ilength = 0;
	list1.isize = isize;
	if(list1.pdatas == NULL){
		list1.isize = 0;
	}
	return list1;
};

void clear(struct List *plist1){
	plist1->ilength = 0;
}

void destroy(struct List *plist){
	free(plist->pdatas);
	plist->pdatas = NULL;
	plist->isize = 0;
}

struct List copy(struct List slist){
	int i;
	struct List dlist;
	dlist = create(slist.isize);
	if(dlist.pdatas == NULL)return dlist;
	for(i=0; i<slist.ilength; i++)dlist.pdatas[i]=slist.pdatas[i];
	dlist.ilength = i;
	return dlist;
}

int empty(struct List list){
	return (list.ilength == 0);
}

int length(struct List list){
	return list.ilength;
}

position positionbegin(struct List list){
	return list.pdatas;
}

position positionend(struct List list){
	return list.pdatas+list.ilength;
}

position nextposition(struct List list, position pos){
	return pos+1;
}

position locateposition(struct List list, int i){
	if(i>=1 && i<=list.ilength)return list.pdatas+(i-1);
	return list.pdatas+list.ilength;
}

position locateelem(struct List list,DE e){
	int i;
	for(i=0; i<list.ilength; i++)if(list.pdatas[i] == e){
		return list.pdatas+i;
	}
	return list.pdatas+list.ilength;
}

DE getelem(struct List list,position pos){
	assert(pos != positionend(list));
	return*pos;
}

void setelem(struct List list, position pos, DE e){
	assert(pos != positionend(list));
	*pos = e;
}

int insertbefore(struct List *plist, position pos, DE e){
	int i;
	if(plist->isize == plist->ilength){
		struct List newlist = create(2*plist->isize);
		if(newlist.pdatas == NULL){
			return 0;	
		}
		for( i=0; i<plist->ilength; i++)newlist.pdatas[i] = plist->pdatas[i];
		newlist.ilength = i;
		pos = newlist.pdatas+(pos-plist->pdatas);
		destroy(plist);
		*plist = newlist;
	}
	assert(plist->isize>plist->ilength);
	position lastpos = plist->pdatas+plist->ilength;
	while(pos != lastpos){
		*lastpos = *(lastpos-1);
		--lastpos;
	}
	*pos = e;
	++plist->ilength;
	return 1;
}

void Delete(struct List*plist,position pos){
	position endpos = positionend(*plist);
	assert(pos != endpos);
	++pos;
	while(pos != endpos){
		*(pos-1) = *pos;
		++pos;
	}
	--plist->ilength;
}

void Print( struct List list ){
	printf("(");
	position pos = positionbegin(list);
	if(pos != positionend(list)){
		printf("%d", getelem(list, pos));
		pos = nextposition(list, pos);
		
	}
	if(pos != positionend(list)){
		printf(",%d", getelem(list, pos));
		pos = nextposition(list, pos);
	}
	printf(")\n");
}
